package com.battery.system.service.battery.impl;

import com.battery.common.core.text.Convert;
import com.battery.common.enums.IncomeTypeEnum;
import com.battery.common.enums.PointTypeEnum;
import com.battery.common.enums.ShareLevelEnum;
import com.battery.common.enums.YesOrNoEnum;
import com.battery.common.utils.DateUtils;
import com.battery.system.domain.*;
import com.battery.system.domain.BO.IncomeBO;
import com.battery.system.domain.VO.*;
import com.battery.system.domain.VO.StoreCount;
import com.battery.system.mapper.*;
import com.battery.system.service.ISysConfigService;
import com.battery.system.service.battery.IIncomeService;
import com.battery.system.service.impl.BaseServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.n3r.idworker.Sid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 收益Service业务层处理
 *
 * @author battery
 * @date 2021-01-22
 */
@Service
public class IncomeServiceImpl extends BaseServiceImpl<Income> implements IIncomeService {

    @Autowired
    private IncomeMapper incomeMapper;


    @Autowired
    private UsedMapper usedMapper;


    @Autowired
    private ProjectMapper projectMapper;


    @Autowired
    private PartnerMapper partnerMapper;


    @Autowired
    private Sid sid;


    @Autowired
    private ISysConfigService configService;


    @Autowired
    private MerchantMapper merchantMapper;


    @Autowired
    private UsedBasicsMapper usedBasicsMapper;


    @Autowired
    private PointsDetailMapper pointsDetailMapper;


    @Autowired
    private OrderMapper orderMapper;


    @Autowired
    private RefundOrderMapper refundOrderMapper;

    @Autowired
    private DeviceMapper deviceMapper;


    @Autowired
    private PreCostMapper preCostMapper;


    @Autowired
    private EventMapper eventMapper;

    /**
     * 查询收益
     *
     * @param id 收益ID
     * @return 收益
     */
    @Override
    public Income selectIncomeById(String id) {
        return incomeMapper.selectIncomeById(id);
    }

    /**
     * 查询收益列表
     *
     * @param income 收益
     * @return 收益
     */
    @Override
    public List<Income> selectIncomeList(Income income) {
        return incomeMapper.selectIncomeList(income);
    }

    /**
     * 新增收益
     *
     * @param income 收益
     * @return 结果
     */
    @Override
    public int insertIncome(Income income) {
        return incomeMapper.insertIncome(income);
    }

    /**
     * 修改收益
     *
     * @param income 收益
     * @return 结果
     */
    @Override
    public int updateIncome(Income income) {
        return incomeMapper.updateIncome(income);
    }

    /**
     * 删除收益对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteIncomeByIds(String ids) {
        return incomeMapper.deleteIncomeByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除收益信息
     *
     * @param id 收益ID
     * @return 结果
     */
    @Override
    public int deleteIncomeById(String id) {
        return incomeMapper.deleteIncomeById(id);
    }


    @Override
    public BillDetails selectIncomeSum(Map<String, String> map) {
        return incomeMapper.selectIncomeSum(map);
    }

    @Override
    public List<BillDetails> selectIncomeGroup(Map<String, String> map) {
        return incomeMapper.selectIncomeGroup(map);
    }

    @Override
    public IncomeCount selectIncomeByCount(Map<String, String> map) {
        return incomeMapper.selectIncomeByCount(map);
    }

    @Override
    public IncomeCount selectIncomeByCountDetails(String id, int type, int toDay, String start, String end) {
        return incomeMapper.selectIncomeByCountDetails(id, type, toDay, start, end);
    }

    @Override
    public List<IncomeCount> selectIncomeByMyIncome(Map<String, String> map) {
        return incomeMapper.selectIncomeByMyIncome(map);
    }

    @Override
    public PartnerCount selectPartnerByStoreCount(String id) {
        return incomeMapper.selectPartnerByStoreCount(id);
    }

    @Override
    public List<StoreCount> selectPartnerByStoreGroup(Map<String, String> map) {
        return incomeMapper.selectPartnerByStoreGroup(map);
    }


    /**
     * 进行分润操作 (
     * 对于每一级，针对下一级都是100， 从上至下 层层控制
     * )
     * <p>
     * TODO TODO TODO 99元订单，积分给直营合作商 平台抽成对应金额，然后剩下的金额除商户其他的正常分成
     *
     * @param used_id  租借记录ID
     * @param order_id 支付订单ID
     */
    @Transactional
    @Override
    public void shareMoney(String used_id, String order_id) {
        // 查询该笔租借订单是否已有分润
        Example exampleIncomeExist = new Example(Income.class);
        Example.Criteria criteria = exampleIncomeExist.createCriteria();
        criteria.andEqualTo("usedId", used_id);
        int incomeSize = incomeMapper.selectCountByExample(exampleIncomeExist);
        if (incomeSize > 0) {
            // 已经存在分润，则不进行分润操作
            return;
        }
        // 对于每一级别 分成比例都是 100
        Used used = usedMapper.selectByPrimaryKey(used_id);
        Integer isM = used.getIsM();
        if (isM == 1) {
            return;
        }

        Project project = projectMapper.selectByPrimaryKey(used.getProjectId());
        BigDecimal amountPaid = used.getAmountPaid(); // 实付金额 即为 实际分润金额
        Date shareTime = DateUtils.getNowDate(); // 分成时间
        UsedBasics basics = usedBasicsMapper.selectByPrimaryKey(used_id);

        if ("0".equals(used.getMerchantId()) || StringUtils.isBlank(used.getMerchantId())
                || "0".equals(used.getPartnerId()) || StringUtils.isBlank(used.getPartnerId())
                || "0".equals(used.getStoreId()) || StringUtils.isBlank(used.getStoreId())
        ) {
            // TODO 如果存在此种情况，直接分润收益归平台所有
            String id = sid.nextShort();
            Income income = new Income();
            income.setId(id);
            income.setUsedId(used.getId());
            income.setOrderId(order_id);
            income.setTotalAmount(amountPaid); // 分润总金额
            income.setProjectId(used.getProjectId());
            income.setPartnerId(used.getPartnerId()); //  合作商ID
            income.setMerchantId(used.getMerchantId());
            income.setStoreId(used.getStoreId());
            income.setShareLevel(ShareLevelEnum.PROJECT.type);
            income.setIncomeType(IncomeTypeEnum.NOT_DEPLOYED_INCOME.type); // 未部署设备分润
            income.setShareTime(shareTime);
            income.setUserAppId(used.getAppUserId());
            income.setShareBrokerage(null);
            income.setBeforeMoney(project.getCashoutMoney()); // 分润前金额
            income.setAfterMoney(project.getCashoutMoney().add(amountPaid)); // 分润后金额
            income.setShareMoney(amountPaid); // 分润金额
            income.setDeviceId(basics.getRentDeviceId());
            income.setDirectPartnerId(used.getPartnerId());
            incomeMapper.insertIncome(income);

            Project projectUpdate = new Project();
            projectUpdate.setId(project.getId());
            projectUpdate.setNotDeployedMoney(project.getNotDeployedMoney().add(amountPaid));
            projectMapper.updateByPrimaryKeySelective(projectUpdate);
            return;
        }

        if (amountPaid.compareTo(BigDecimal.ZERO) == 0) {
            // 金额为0,不分成
            return;
        }
        BigDecimal surplusAmout = amountPaid; // 剩余金额


        // TODO TODO 分成还需要考虑活动设备
        BigDecimal ptAddShareRate = BigDecimal.ZERO;
        if (used.getIsActivity() == 1) {
            // 该笔订单是活动订单
            Device borDev = deviceMapper.selectByPrimaryKey(basics.getRentDeviceId());
            if (borDev != null) {
                Event event = eventMapper.selectByPrimaryKey(borDev.getEventId());
                if (event != null) {
                    ptAddShareRate = event.getEventShare();
                }
            }
        }

        Partner partner = partnerMapper.selectByPrimaryKey(used.getPartnerId());
        // 开始平台分润
        if (amountPaid.subtract(new BigDecimal(99)).compareTo(BigDecimal.ZERO) == 0) {
            // 金额达到99元
            /**
             * 积分类型
             * 0 产生订单
             * 1 向平台兑换商品
             * 2 向其他合作商兑换商品
             * 3 小宝被购买
             * 4 被购买小宝退款
             * 5 其他合作商向我兑换物品
             * 6 平台赠送
             * 7 平台扣除
             * 8 异代理归还赠送
             * 9 异代理归还扣除
             */
            // TODO TODO 平台抽成之后，给直营合作商加积分

            // 收益来源 1 收益  2 退款  3 平台抽成 4 平台抽成退款

            // 只要是99元，平台抽取之后，剩下的金额合作商层层分，同时积分加给合作商

            // 99元订单-平台抽取金额 ----------------> start
            BigDecimal projectExtractMoney = new BigDecimal(configService.selectConfigByKeyNoCache("sys.extract.money"));

            String id = sid.nextShort();
            Income income = new Income();
            income.setId(id);
            income.setUsedId(used.getId());
            income.setOrderId(order_id);
            income.setTotalAmount(amountPaid); // 分润总金额
            income.setProjectId(used.getProjectId());
            income.setPartnerId(used.getPartnerId()); //  合作商ID
            income.setMerchantId(used.getMerchantId());
            income.setStoreId(used.getStoreId());
            income.setShareLevel(ShareLevelEnum.PROJECT.type);
            income.setIncomeType(IncomeTypeEnum.PROJECT_EXTRACT.type); // 平台抽取金额
            income.setShareTime(shareTime);
            income.setUserAppId(used.getAppUserId());
            income.setShareBrokerage(null);
            income.setBeforeMoney(project.getCashoutMoney()); // 分润前金额
            income.setAfterMoney(project.getCashoutMoney().add(projectExtractMoney)); // 分润后金额
            income.setShareMoney(projectExtractMoney); // 分润金额
            income.setDeviceId(basics.getRentDeviceId());
            income.setDirectPartnerId(partner.getId());
            incomeMapper.insertIncome(income);

            Project updateProject = new Project();
            updateProject.setId(project.getId());
            updateProject.setCashoutMoney(project.getCashoutMoney().add(projectExtractMoney)); // 保存项目-可提现金额
            updateProject.setExtractMoney(project.getExtractMoney().add(projectExtractMoney)); // 抽取收益金额
            projectMapper.updateByPrimaryKeySelective(updateProject);
            // 99元订单-平台抽取金额 ----------------> end


            BigDecimal partnerGetMoney = amountPaid.subtract(projectExtractMoney); // 剩下的金额

            // 合作商抽取金额 ----------------------> start
            if (StringUtils.isBlank(partner.getParentId()) || "0".equals(partner.getParentId())) {
                // TODO 注意：这里是合作商的直营商户提供的99元收益

                String partnerIncomeId = sid.nextShort();
                Income partnerIncome = new Income();
                partnerIncome.setId(partnerIncomeId);
                partnerIncome.setUsedId(used.getId());
                partnerIncome.setOrderId(order_id);
                partnerIncome.setTotalAmount(amountPaid); // 分润总金额99 - 平台抽取
                partnerIncome.setProjectId(used.getProjectId());
                partnerIncome.setPartnerId(used.getPartnerId()); //  合作商ID
                partnerIncome.setMerchantId(used.getMerchantId());
                partnerIncome.setStoreId(used.getStoreId());
                partnerIncome.setShareLevel(ShareLevelEnum.PARTNER.type);
                partnerIncome.setIncomeType(IncomeTypeEnum.INCOME.type); // 合作商99元抽取金额收益
                partnerIncome.setShareTime(shareTime);
                partnerIncome.setUserAppId(used.getAppUserId());
                partnerIncome.setShareBrokerage(new BigDecimal(100)); // 分润比例
                partnerIncome.setBeforeMoney(partner.getCashoutMoney()); // 分润前金额
                partnerIncome.setAfterMoney(partner.getCashoutMoney().add(partnerGetMoney)); // 分润后金额
                partnerIncome.setShareMoney(partnerGetMoney); // 分润金额
                partnerIncome.setDeviceId(basics.getRentDeviceId());
                partnerIncome.setDirectPartnerId(partner.getId()); // 直营合作商ID
                incomeMapper.insertIncome(partnerIncome);

                Partner partnerUpdatte = new Partner();
                partnerUpdatte.setId(partner.getId());
                partnerUpdatte.setCashoutMoney(partner.getCashoutMoney().add(partnerGetMoney)); // 可提现金额
                partnerUpdatte.setDirectTurnover(partner.getDirectTurnover().add(amountPaid)); // 直营商户贡献营业额
                partnerUpdatte.setDirectIncome(partner.getDirectIncome().add(partnerGetMoney)); // 直营商户贡献收益
                partnerUpdatte.setPreincome(partner.getPreincome().add(projectExtractMoney)); // 给上级贡献收益，即为平台分成金额
                partnerMapper.updateByPrimaryKeySelective(partnerUpdatte);


                // TODO 开始增加积分 start 给直营合作商增加
                // TODO TODO 这里要判断
                int point = Integer.parseInt(configService.selectConfigByKeyNoCache("sys.extract.point"));
                boolean flag = false;
                UsedBasics usedBasics = usedBasicsMapper.selectByPrimaryKey(used_id);
                if (usedBasics.getRentDeviceSn().equals(usedBasics.getBackDeviceSn())) {
                    // 租借的机柜SN跟归还的机柜SN一致
                    flag = true;
                } else {
                    Device borrowDev = deviceMapper.selectByPrimaryKey(basics.getRentDeviceId());
                    Device returnDev = deviceMapper.selectByPrimaryKey(basics.getBackDeviceId());
                    if (borrowDev.getPartnerId().equals(returnDev.getPartnerId())) {
                        flag = true;
                    } else {
                        //  归还给异代理， 异代理减积分 本代理增加积分
                        Partner returnPartner = partnerMapper.selectByPrimaryKey(returnDev.getPartnerId());

                        // 先处理异代理减积分, 异代理归还扣除
                        PointsDetail rsPointsDetail = new PointsDetail();
                        rsPointsDetail.setId(sid.nextShort());
                        rsPointsDetail.setPointType(PointTypeEnum.RETURN_DEDUCTION_OF_DIFFERENT_AGENTS.type); // 异代理归还扣除
                        rsPointsDetail.setPoints((-1) * point);
                        rsPointsDetail.setCreateTime(shareTime); // 创建时间
                        rsPointsDetail.setUsedId(used_id);
                        rsPointsDetail.setOrderId(order_id);
                        rsPointsDetail.setAppUserId(used.getAppUserId());
                        rsPointsDetail.setSourceType(1); // 合作商类型 0 平台 1 合作商
                        rsPointsDetail.setSourceId(partner.getId());
                        rsPointsDetail.setWinnerType(1);
                        rsPointsDetail.setWinnerId(returnPartner.getId());
                        pointsDetailMapper.insertPointsDetail(rsPointsDetail);


                        // 异代理减积分
                        Partner partnerUpdatteRs = new Partner();
                        partnerUpdatteRs.setPoint(returnPartner.getPoint() - point); // 减积分
                        partnerUpdatteRs.setId(returnPartner.getId());
                        partnerMapper.updateByPrimaryKeySelective(partnerUpdatteRs);


                        PointsDetail borrowPointsDetail = new PointsDetail();
                        borrowPointsDetail.setId(sid.nextShort());
                        borrowPointsDetail.setPointType(PointTypeEnum.RETURN_AND_PRESENT_BY_DIFFERENT_AGENTS.type); // 异代理归还赠送
                        borrowPointsDetail.setPoints(point);
                        borrowPointsDetail.setCreateTime(shareTime); // 创建时间
                        borrowPointsDetail.setUsedId(used_id);
                        borrowPointsDetail.setOrderId(order_id);
                        borrowPointsDetail.setAppUserId(used.getAppUserId());
                        borrowPointsDetail.setSourceType(1); // 合作商类型 0 平台 1 合作商
                        borrowPointsDetail.setSourceId(returnPartner.getId());
                        borrowPointsDetail.setWinnerType(1);
                        borrowPointsDetail.setWinnerId(partner.getId());
                        pointsDetailMapper.insertPointsDetail(borrowPointsDetail);

                        // 给合作商增加积分
                        Partner partnerUpdate = new Partner();
                        partnerUpdate.setPoint(partner.getPoint() + point); // 增加积分
                        partnerUpdate.setId(partner.getId());
                        partnerMapper.updateByPrimaryKeySelective(partnerUpdate);
                    }
                }
                // 开始增加积分 end

                if (flag) {
                    PointsDetail pointsDetail = new PointsDetail();
                    String pointDetailId = sid.nextShort();
                    pointsDetail.setId(pointDetailId);
                    pointsDetail.setPointType(PointTypeEnum.XIAOBAO_IS_BOUGHT.type); // 小宝被购买
                    pointsDetail.setPoints(point);
                    pointsDetail.setCreateTime(shareTime); // 创建时间
                    pointsDetail.setUsedId(used_id);
                    pointsDetail.setOrderId(order_id);
                    pointsDetail.setAppUserId(used.getAppUserId());
                    pointsDetail.setSourceType(1); // 合作商类型 0 平台 1 合作商
                    pointsDetail.setSourceId(partner.getId());
                    pointsDetail.setWinnerType(1);
                    pointsDetail.setWinnerId(partner.getId());
                    pointsDetailMapper.insertPointsDetail(pointsDetail);

                    // 给合作商增加积分
                    partnerUpdatte.setPoint(partner.getPoint() + point); // 增加积分
                    partnerUpdatte.setId(partner.getId());
                }

            } else {
                // TODO 存在多级合作商
                // 获取该合作商的上级所有代理信息

                BigDecimal partnerGetMoneyFc = partnerGetMoney;

                List<Partner> partners = partnerMapper.selectAllParents(partner.getId());
                if (partners != null && partners.size() > 0) {
                    // 获取顶级合作商信息
                    int partnerSize = partners.size();

                    // 计算除开商户直营的合作商分润金额
                    for (int i = 0; i <= partnerSize - 1; i++) {
                        Partner partnerLv1 = partners.get(i); // 上级合作商

                        Partner partnerLv2 = null;
                        if (partnerSize == 1) {
                            // TODO 该合作商只存在一个上级合作商
                            partnerLv2 = partner; // 下级合作商
                        } else {
                            partnerLv2 = partners.get(i + 1); // 下级合作商
                        }

                        BigDecimal partnerLv1GetMoney = partnerGetMoneyFc.multiply(new BigDecimal(100).subtract(partnerLv2.getShareRatio())).divide(new BigDecimal(100));

                        BigDecimal partnerLv1ActualShareBrokerage = partnerLv1GetMoney.divide(partnerGetMoney).multiply(new BigDecimal(100));
                        String partnerIncomeIdLv1 = sid.nextShort();
                        Income partnerIncomeLv1 = new Income();
                        partnerIncomeLv1.setId(partnerIncomeIdLv1);
                        partnerIncomeLv1.setUsedId(used.getId());
                        partnerIncomeLv1.setOrderId(order_id);
                        partnerIncomeLv1.setTotalAmount(amountPaid); // 分润总金额99
                        partnerIncomeLv1.setProjectId(used.getProjectId());
                        partnerIncomeLv1.setPartnerId(partnerLv1.getId()); //  合作商ID
                        partnerIncomeLv1.setMerchantId(used.getMerchantId());
                        partnerIncomeLv1.setStoreId(used.getStoreId());
                        partnerIncomeLv1.setShareLevel(ShareLevelEnum.PARTNER.type);
                        partnerIncomeLv1.setIncomeType(IncomeTypeEnum.INCOME.type);
                        partnerIncomeLv1.setShareTime(shareTime);
                        partnerIncomeLv1.setUserAppId(used.getAppUserId());
                        partnerIncomeLv1.setShareBrokerage(partnerLv1ActualShareBrokerage); // 分润比例
                        partnerIncomeLv1.setBeforeMoney(partnerLv1.getCashoutMoney()); // 分润前金额
                        partnerIncomeLv1.setAfterMoney(partnerLv1.getCashoutMoney().add(partnerLv1GetMoney)); // 分润后金额
                        partnerIncomeLv1.setShareMoney(partnerLv1GetMoney); // 分润金额
                        partnerIncomeLv1.setDeviceId(basics.getRentDeviceId());
                        partnerIncomeLv1.setDirectPartnerId(partner.getId()); // 直营合作商ID
                        incomeMapper.insertIncome(partnerIncomeLv1);

                        Partner partnerLv1Updatte = new Partner();
                        partnerLv1Updatte.setId(partnerLv1.getId());
                        partnerLv1Updatte.setCashoutMoney(partnerLv1.getCashoutMoney().add(partnerLv1GetMoney)); // 可提现金额
                        partnerLv1Updatte.setJuniorTurnover(partnerLv1.getJuniorTurnover().add(amountPaid)); // 下级贡献营业额
                        partnerLv1Updatte.setJuniorIncome(partnerLv1.getJuniorIncome().add(partnerLv1GetMoney)); // 下级贡献收益
                        if (i == 0) {
                            // 是顶级合作商，那么上级为平台
                            partnerLv1Updatte.setPreincome(partnerLv1.getPreincome().add(projectExtractMoney)); // 给上级贡献收益
                        } else {
                            Example example = new Example(Income.class);
                            Example.Criteria criteriaIncome = example.createCriteria();

                            criteriaIncome.andEqualTo("usedId", used_id);
                            criteriaIncome.andEqualTo("orderId", order_id);
                            criteriaIncome.andEqualTo("totalAmount", amountPaid); // 99元的抽成
                            criteriaIncome.andEqualTo("partnerId", partners.get(i - 1).getId());
                            criteriaIncome.andEqualTo("shareLevel", ShareLevelEnum.PARTNER.type);
                            criteriaIncome.andEqualTo("incomeType", IncomeTypeEnum.INCOME.type);
                            criteriaIncome.andEqualTo("userAppId", used.getAppUserId());
                            Income superiorIncome = incomeMapper.selectOneByExample(example);
                            partnerLv1Updatte.setPreincome(partnerLv1.getPreincome().add(superiorIncome.getShareMoney())); // 给上级贡献收益
                        }
                        partnerMapper.updateByPrimaryKeySelective(partnerLv1Updatte);
                        // 计算剩余的金额
                        partnerGetMoneyFc = partnerGetMoneyFc.subtract(partnerLv1GetMoney);

                    }

                    // 计算直营合作商分润 ========================= start

                    // 查询商户分润

                    Partner partnerDirect = partner; // 直营合作商
                    BigDecimal directPartnerGetMoney = partnerGetMoneyFc;

                    // 合作商实际分润比例
                    BigDecimal partnerActualShareBrokerage = directPartnerGetMoney.divide(partnerGetMoney).multiply(new BigDecimal(100));
                    String partnerIncomeId = sid.nextShort();
                    Income partnerIncome = new Income();
                    partnerIncome.setId(partnerIncomeId);
                    partnerIncome.setUsedId(used.getId());
                    partnerIncome.setOrderId(order_id);
                    partnerIncome.setTotalAmount(amountPaid); // 分润总金额
                    partnerIncome.setProjectId(used.getProjectId());
                    partnerIncome.setPartnerId(partnerDirect.getId()); //  合作商ID
                    partnerIncome.setMerchantId(used.getMerchantId());
                    partnerIncome.setStoreId(used.getStoreId());
                    partnerIncome.setShareLevel(ShareLevelEnum.PARTNER.type);
                    partnerIncome.setIncomeType(IncomeTypeEnum.INCOME.type);
                    partnerIncome.setShareTime(shareTime);
                    partnerIncome.setUserAppId(used.getAppUserId());
                    partnerIncome.setShareBrokerage(partnerActualShareBrokerage); // 分润比例
                    partnerIncome.setBeforeMoney(partnerDirect.getCashoutMoney()); // 分润前金额
                    partnerIncome.setAfterMoney(partnerDirect.getCashoutMoney().add(partnerGetMoney)); // 分润后金额
                    partnerIncome.setShareMoney(partnerGetMoney); // 分润金额
                    partnerIncome.setDeviceId(basics.getRentDeviceId());
                    partnerIncome.setDirectPartnerId(partnerDirect.getId());
                    incomeMapper.insertIncome(partnerIncome);

                    // TODO 开始增加积分 start 给直营合作商增加
                    // TODO TODO 这里要判断
                    Integer point = Integer.parseInt(configService.selectConfigByKeyNoCache("sys.extract.point"));
                    boolean flag = false;
                    UsedBasics usedBasics = usedBasicsMapper.selectByPrimaryKey(used_id);
                    if (usedBasics.getRentDeviceSn().equals(usedBasics.getBackDeviceSn())) {
                        // 租借的机柜SN跟归还的机柜SN一致
                        flag = true;
                    } else {
                        Device borrowDev = deviceMapper.selectByPrimaryKey(basics.getRentDeviceId());
                        Device returnDev = deviceMapper.selectByPrimaryKey(basics.getBackDeviceId());
                        if (borrowDev.getPartnerId().equals(returnDev.getPartnerId())) {
                            flag = true;
                        } else {
                            //  归还给异代理， 异代理减积分 本代理增加积分
                            Partner returnPartner = partnerMapper.selectByPrimaryKey(returnDev.getPartnerId());

                            // 先处理异代理减积分, 异代理归还扣除
                            PointsDetail rsPointsDetail = new PointsDetail();
                            rsPointsDetail.setId(sid.nextShort());
                            rsPointsDetail.setPointType(PointTypeEnum.RETURN_DEDUCTION_OF_DIFFERENT_AGENTS.type); // 异代理归还扣除
                            rsPointsDetail.setPoints((-1) * point);
                            rsPointsDetail.setCreateTime(shareTime); // 创建时间
                            rsPointsDetail.setUsedId(used_id);
                            rsPointsDetail.setOrderId(order_id);
                            rsPointsDetail.setAppUserId(used.getAppUserId());
                            rsPointsDetail.setSourceType(1); // 合作商类型 0 平台 1 合作商
                            rsPointsDetail.setSourceId(partner.getId());
                            rsPointsDetail.setWinnerType(1);
                            rsPointsDetail.setWinnerId(returnPartner.getId());
                            pointsDetailMapper.insertPointsDetail(rsPointsDetail);


                            // 异代理减积分
                            Partner partnerUpdatteRs = new Partner();
                            partnerUpdatteRs.setPoint(returnPartner.getPoint() - point); // 减积分
                            partnerUpdatteRs.setId(returnPartner.getId());
                            partnerMapper.updateByPrimaryKeySelective(partnerUpdatteRs);


                            PointsDetail borrowPointsDetail = new PointsDetail();
                            borrowPointsDetail.setId(sid.nextShort());
                            borrowPointsDetail.setPointType(PointTypeEnum.RETURN_AND_PRESENT_BY_DIFFERENT_AGENTS.type); // 异代理归还赠送
                            borrowPointsDetail.setPoints(point);
                            borrowPointsDetail.setCreateTime(shareTime); // 创建时间
                            borrowPointsDetail.setUsedId(used_id);
                            borrowPointsDetail.setOrderId(order_id);
                            borrowPointsDetail.setAppUserId(used.getAppUserId());
                            borrowPointsDetail.setSourceType(1); // 合作商类型 0 平台 1 合作商
                            borrowPointsDetail.setSourceId(returnPartner.getId());
                            borrowPointsDetail.setWinnerType(1);
                            borrowPointsDetail.setWinnerId(partner.getId());
                            pointsDetailMapper.insertPointsDetail(borrowPointsDetail);

                            // 给合作商增加积分
                            Partner partnerUpdate = new Partner();
                            partnerUpdate.setPoint(partner.getPoint() + point); // 增加积分
                            partnerUpdate.setId(partner.getId());
                            partnerMapper.updateByPrimaryKeySelective(partnerUpdate);
                        }
                    }
                    // 开始增加积分 end


                    Partner partnerUpdatte = new Partner();
                    partnerUpdatte.setId(partnerDirect.getId());
                    partnerUpdatte.setCashoutMoney(partnerDirect.getCashoutMoney().add(partnerGetMoney)); // 可提现金额
                    partnerUpdatte.setDirectTurnover(partnerDirect.getDirectTurnover().add(amountPaid)); // 直营商户贡献营业额
                    partnerUpdatte.setDirectIncome(partnerDirect.getDirectIncome().add(partnerGetMoney)); // 直营商户贡献收益

                    Example example = new Example(Income.class);
                    Example.Criteria criteriaIncome = example.createCriteria();

                    criteriaIncome.andEqualTo("usedId", used_id);
                    criteriaIncome.andEqualTo("orderId", order_id);
                    criteriaIncome.andEqualTo("totalAmount", amountPaid); // 99元的抽成
                    criteriaIncome.andEqualTo("partnerId", partnerDirect.getParentId());
                    criteriaIncome.andEqualTo("shareLevel", ShareLevelEnum.PARTNER.type);
                    criteriaIncome.andEqualTo("incomeType", IncomeTypeEnum.INCOME.type);
                    criteriaIncome.andEqualTo("userAppId", used.getAppUserId());
                    Income superiorIncome = incomeMapper.selectOneByExample(example);
                    partnerUpdatte.setPreincome(partnerDirect.getPreincome().add(superiorIncome.getShareMoney())); // 给上级贡献收益

                    if (flag) {
                        PointsDetail pointsDetail = new PointsDetail();
                        String pointDetailId = sid.nextShort();
                        pointsDetail.setId(pointDetailId);
                        pointsDetail.setPointType(PointTypeEnum.XIAOBAO_IS_BOUGHT.type); // 小宝被购买
                        pointsDetail.setPoints(point);
                        pointsDetail.setCreateTime(shareTime); // 创建时间
                        pointsDetail.setUsedId(used_id);
                        pointsDetail.setOrderId(order_id);
                        pointsDetail.setAppUserId(used.getAppUserId());
                        pointsDetail.setSourceType(1); // 合作商类型 0 平台 1 合作商
                        pointsDetail.setSourceId(partner.getId());
                        pointsDetail.setWinnerType(1);
                        pointsDetail.setWinnerId(partner.getId());
                        pointsDetailMapper.insertPointsDetail(pointsDetail);


                        // 给合作商增加积分
                        partnerUpdatte.setPoint(partnerUpdatte.getPoint() + point); // 增加积分
                        partnerUpdatte.setId(partner.getId());
                    }
                    partnerMapper.updateByPrimaryKeySelective(partnerUpdatte);


                    // 计算直营合作商分润 ========================= end
                }
            }
            // 合作商抽取金额 ----------------------> end
            return;
        }

        BigDecimal projectShareRatio = BigDecimal.ZERO; // 平台分润比例
        BigDecimal shareRatio = BigDecimal.ZERO; //
        int partnerSize = 0;

        List<Partner> partners = null;
        if (StringUtils.isBlank(partner.getParentId()) || "0".equals(partner.getParentId())) {

            // TODO 注意：这里是合作商的直营商户提供的收益

            // 该合作商不存在上级合作商ID
            projectShareRatio = partner.getProjectShareRatio().add(ptAddShareRate); // 平台分润比例 + 活动分润
            // 开始平台分润，得到分成后剩余金额
            // ================== 平台分成 start ========================

            // 计算平台获取到的分润
            BigDecimal projectGetMoney = amountPaid.multiply(projectShareRatio.divide(new BigDecimal(100)));

            String id = sid.nextShort();
            Income income = new Income();
            income.setId(id);
            income.setUsedId(used.getId());
            income.setOrderId(order_id);
            income.setTotalAmount(amountPaid); // 分润总金额
            income.setProjectId(used.getProjectId());
            income.setPartnerId(used.getPartnerId()); //  合作商ID
            income.setMerchantId(used.getMerchantId());
            income.setStoreId(used.getStoreId());
            income.setShareLevel(ShareLevelEnum.PROJECT.type);
            income.setIncomeType(IncomeTypeEnum.INCOME.type);
            income.setShareTime(shareTime);
            income.setUserAppId(used.getAppUserId());
            income.setShareBrokerage(projectShareRatio);
            income.setBeforeMoney(project.getCashoutMoney()); // 分润前金额
            income.setAfterMoney(project.getCashoutMoney().add(projectGetMoney)); // 分润后金额
            income.setShareMoney(projectGetMoney); // 分润金额
            income.setDeviceId(basics.getRentDeviceId());
            income.setDirectPartnerId(partner.getId());
            incomeMapper.insertIncome(income);

            Project updateProject = new Project();
            updateProject.setId(project.getId());
            updateProject.setCashoutMoney(project.getCashoutMoney().add(projectGetMoney)); // 保存项目-可提现金额
            updateProject.setTotalRevenue(project.getTotalRevenue().add(projectGetMoney));
            projectMapper.updateByPrimaryKeySelective(updateProject);

            surplusAmout = amountPaid.subtract(projectGetMoney);

            // ================== 平台分成 end ========================

            // 查询商户分润
            Merchant merchant = merchantMapper.selectByPrimaryKey(used.getMerchantId());
            BigDecimal merchantShareRatio = merchant.getShareRatio();

            // 开始合作商分成 ------------------- start

            BigDecimal partnerGetMoney = ((new BigDecimal(100).subtract(merchantShareRatio)).divide(new BigDecimal(100))).multiply(surplusAmout);

            // 合作商实际分润比例
            BigDecimal partnerActualShareBrokerage = partnerGetMoney.divide(amountPaid).multiply(new BigDecimal(100));
            String partnerIncomeId = sid.nextShort();
            Income partnerIncome = new Income();
            partnerIncome.setId(partnerIncomeId);
            partnerIncome.setUsedId(used.getId());
            partnerIncome.setOrderId(order_id);
            partnerIncome.setTotalAmount(amountPaid); // 分润总金额
            partnerIncome.setProjectId(used.getProjectId());
            partnerIncome.setPartnerId(used.getPartnerId()); //  合作商ID
            partnerIncome.setMerchantId(used.getMerchantId());
            partnerIncome.setStoreId(used.getStoreId());
            partnerIncome.setShareLevel(ShareLevelEnum.PARTNER.type);
            partnerIncome.setIncomeType(IncomeTypeEnum.INCOME.type);
            partnerIncome.setShareTime(shareTime);
            partnerIncome.setUserAppId(used.getAppUserId());
            partnerIncome.setShareBrokerage(partnerActualShareBrokerage); // 分润比例
            partnerIncome.setBeforeMoney(partner.getCashoutMoney()); // 分润前金额
            partnerIncome.setAfterMoney(partner.getCashoutMoney().add(partnerGetMoney)); // 分润后金额
            partnerIncome.setShareMoney(partnerGetMoney); // 分润金额
            partnerIncome.setDeviceId(basics.getRentDeviceId());
            partnerIncome.setDirectPartnerId(partner.getId());
            incomeMapper.insertIncome(partnerIncome);


            Partner partnerUpdatte = new Partner();
            partnerUpdatte.setId(partner.getId());
            partnerUpdatte.setCashoutMoney(partner.getCashoutMoney().add(partnerGetMoney)); // 可提现金额
            partnerUpdatte.setDirectTurnover(partner.getDirectTurnover().add(amountPaid)); // 直营商户贡献营业额
            partnerUpdatte.setDirectIncome(partner.getDirectIncome().add(partnerGetMoney)); // 直营商户贡献收益
            partnerUpdatte.setPreincome(partner.getPreincome().add(projectGetMoney)); // 给上级贡献收益，即为平台分成金额

            partnerMapper.updateByPrimaryKeySelective(partnerUpdatte);
            // 开始合作商分成 -------------------- end


            // 商户分成 ====================  start

            // 商户获取剩下的金额
            BigDecimal merchantGetMoney = amountPaid.subtract(partnerGetMoney).subtract(projectGetMoney);


            BigDecimal merchantShareBrokerage = merchantGetMoney.divide(amountPaid).multiply(new BigDecimal(100));

            Income merchantIncome = new Income();
            String merchantIncomeId = sid.nextShort();
            merchantIncome.setId(merchantIncomeId);
            merchantIncome.setUsedId(used.getId());
            merchantIncome.setOrderId(order_id);
            merchantIncome.setTotalAmount(amountPaid); // 分润总金额
            merchantIncome.setProjectId(used.getProjectId());
            merchantIncome.setPartnerId(used.getPartnerId()); //  合作商ID
            merchantIncome.setMerchantId(used.getMerchantId());
            merchantIncome.setStoreId(used.getStoreId());
            merchantIncome.setShareLevel(ShareLevelEnum.MERCHANT.type);
            merchantIncome.setIncomeType(IncomeTypeEnum.INCOME.type);
            merchantIncome.setShareTime(shareTime);
            merchantIncome.setUserAppId(used.getAppUserId());
            merchantIncome.setShareBrokerage(merchantShareBrokerage); // 分润比例
            merchantIncome.setBeforeMoney(merchant.getCashoutMoney()); // 分润前金额
            merchantIncome.setAfterMoney(merchant.getCashoutMoney().add(merchantGetMoney)); // 分润后金额
            merchantIncome.setShareMoney(merchantGetMoney); // 分润金额
            merchantIncome.setDeviceId(basics.getRentDeviceId());
            merchantIncome.setDirectPartnerId(partner.getId());
            incomeMapper.insertIncome(merchantIncome);


            if (merchant.getPreCost().compareTo(BigDecimal.ZERO) > 0) {
                // TODO 该商户是预付费商户
                PreCost merchantPreCost = new PreCost();
                merchantPreCost.setUsedId(used.getId());
                merchantPreCost.setOrderId(order_id);
                merchantPreCost.setProjectId(used.getProjectId());
                merchantPreCost.setPartnerId(used.getPartnerId());
                merchantPreCost.setMerchantId(used.getMerchantId());
                merchantPreCost.setStoreId(used.getStoreId());
                merchantPreCost.setPreType(1); // 来源 1 收益  2 退款
                merchantPreCost.setUserAppId(used.getAppUserId());
                merchantPreCost.setShareMoney(amountPaid); // 订单金额
                merchantPreCost.setPreMonery(merchantGetMoney.multiply(new BigDecimal(-1))); // 预付费扣除金额
                merchantPreCost.setShareBrokerage(merchantShareBrokerage); // 分润比例
                merchantPreCost.setBeforeMoney(merchant.getPreCost()); // 预付费扣除前金额
                merchantPreCost.setAfterMoney(merchant.getPreCost().subtract(merchantGetMoney)); // 预付费扣除后金额
                merchantPreCost.setDeviceId(basics.getRentDeviceId());
                merchantPreCost.setCreateTime(shareTime);
                preCostMapper.insertSelective(merchantPreCost);

                // 添加预付费成功，则开始更新商户信息
                Merchant merchantUpdate = new Merchant();
                merchantUpdate.setId(merchant.getId());
                merchantUpdate.setPreCost(merchant.getPreCost().subtract(merchantGetMoney)); // 保存预付费金额
                merchantUpdate.setTotalRevenue(merchant.getTotalRevenue().add(merchantGetMoney));
                merchantMapper.updateByPrimaryKeySelective(merchantUpdate);
            } else {
                Merchant merchantUpdate = new Merchant();
                merchantUpdate.setId(merchant.getId());
                merchantUpdate.setCashoutMoney(merchant.getCashoutMoney().add(merchantGetMoney));
                merchantUpdate.setTotalRevenue(merchant.getTotalRevenue().add(merchantGetMoney));
                merchantMapper.updateByPrimaryKeySelective(merchantUpdate);
            }
            // 商户分成 ====================  end


        } else {
            // 获取该合作商的上级所有代理信息
            partners = partnerMapper.selectAllParents(partner.getId());
            if (partners != null && partners.size() > 0) {
                // 获取顶级合作商信息
                partnerSize = partners.size(); // TODO 这里只能查询出该合作商的上级代理

                Partner partnerNO1 = partners.get(0); // 顶级合作商
                projectShareRatio = partnerNO1.getProjectShareRatio(); // 平台分润比例

                // ================== 平台分成 start ========================

                // 计算平台获取到的分润
                BigDecimal projectGetMoney = amountPaid.multiply(projectShareRatio.divide(new BigDecimal(100)));

                String id = sid.nextShort();
                Income income = new Income();
                income.setId(id);
                income.setUsedId(used.getId());
                income.setOrderId(order_id);
                income.setTotalAmount(amountPaid); // 分润总金额
                income.setProjectId(used.getProjectId());
                income.setPartnerId(used.getPartnerId()); //  合作商ID
                income.setMerchantId(used.getMerchantId());
                income.setStoreId(used.getStoreId());
                income.setShareLevel(ShareLevelEnum.PROJECT.type);
                income.setIncomeType(IncomeTypeEnum.INCOME.type);
                income.setShareTime(shareTime);
                income.setUserAppId(used.getAppUserId());
                income.setShareBrokerage(projectShareRatio);
                income.setBeforeMoney(project.getCashoutMoney()); // 分润前金额
                income.setAfterMoney(project.getCashoutMoney().add(projectGetMoney)); // 分润后金额
                income.setShareMoney(projectGetMoney); // 分润金额
                income.setDeviceId(basics.getRentDeviceId());
                income.setDirectPartnerId(partner.getId());
                incomeMapper.insertIncome(income);

                Project updateProject = new Project();
                updateProject.setId(project.getId());
                updateProject.setCashoutMoney(project.getCashoutMoney().add(projectGetMoney)); // 保存项目-可提现金额
                updateProject.setTotalRevenue(project.getTotalRevenue().add(projectGetMoney));
                projectMapper.updateByPrimaryKeySelective(updateProject);

                surplusAmout = amountPaid.subtract(projectGetMoney);

                // ================== 平台分成 end ========================

                // 计算除开商户直营的合作商分润金额
                for (int i = 0; i <= partnerSize - 1; i++) {
                    Partner partnerLv1 = partners.get(i); // 上级合作商
                    Partner partnerLv2 = null;
                    if (partnerSize == 1) {
                        // TODO 该合作商只存在一个上级合作商
                        partnerLv2 = partner; // 下级合作商
                    } else {
                        partnerLv2 = partners.get(i + 1); // 下级合作商
                    }
                    BigDecimal partnerLv1GetMoney = surplusAmout.multiply(new BigDecimal(100).subtract(partnerLv2.getShareRatio())).divide(new BigDecimal(100));

                    BigDecimal partnerLv1ActualShareBrokerage = partnerLv1GetMoney.divide(amountPaid).multiply(new BigDecimal(100));
                    String partnerIncomeIdLv1 = sid.nextShort();
                    Income partnerIncomeLv1 = new Income();
                    partnerIncomeLv1.setId(partnerIncomeIdLv1);
                    partnerIncomeLv1.setUsedId(used.getId());
                    partnerIncomeLv1.setOrderId(order_id);
                    partnerIncomeLv1.setTotalAmount(amountPaid); // 分润总金额
                    partnerIncomeLv1.setProjectId(used.getProjectId());
                    partnerIncomeLv1.setPartnerId(partnerLv1.getId()); //  合作商ID
                    partnerIncomeLv1.setMerchantId(used.getMerchantId());
                    partnerIncomeLv1.setStoreId(used.getStoreId());
                    partnerIncomeLv1.setShareLevel(ShareLevelEnum.PARTNER.type);
                    partnerIncomeLv1.setIncomeType(IncomeTypeEnum.INCOME.type);
                    partnerIncomeLv1.setShareTime(shareTime);
                    partnerIncomeLv1.setUserAppId(used.getAppUserId());
                    partnerIncomeLv1.setShareBrokerage(partnerLv1ActualShareBrokerage); // 分润比例
                    partnerIncomeLv1.setBeforeMoney(partnerLv1.getCashoutMoney()); // 分润前金额
                    partnerIncomeLv1.setAfterMoney(partnerLv1.getCashoutMoney().add(partnerLv1GetMoney)); // 分润后金额
                    partnerIncomeLv1.setShareMoney(partnerLv1GetMoney); // 分润金额
                    partnerIncomeLv1.setDeviceId(basics.getRentDeviceId());
                    partnerIncomeLv1.setDirectPartnerId(partner.getId());
                    incomeMapper.insertIncome(partnerIncomeLv1);

                    Partner partnerLv1Updatte = new Partner();
                    partnerLv1Updatte.setId(partnerLv1.getId());
                    partnerLv1Updatte.setCashoutMoney(partnerLv1.getCashoutMoney().add(partnerLv1GetMoney)); // 可提现金额
                    partnerLv1Updatte.setJuniorTurnover(partnerLv1.getJuniorTurnover().add(amountPaid)); // 下级贡献营业额
                    partnerLv1Updatte.setJuniorIncome(partnerLv1.getJuniorIncome().add(partnerLv1GetMoney)); // 下级贡献收益
                    if (i == 0) {
                        // 是顶级合作商，那么上级为平台
                        partnerLv1Updatte.setPreincome(partnerLv1.getPreincome().add(projectGetMoney)); // 给上级贡献收益
                    } else {
                        Example example = new Example(Income.class);
                        Example.Criteria criteriaIncome = example.createCriteria();

                        criteriaIncome.andEqualTo("usedId", used_id);
                        criteriaIncome.andEqualTo("orderId", order_id);
                        criteriaIncome.andEqualTo("partnerId", partners.get(i - 1).getId());
                        criteriaIncome.andEqualTo("shareLevel", ShareLevelEnum.PARTNER.type);
                        criteriaIncome.andEqualTo("incomeType", IncomeTypeEnum.INCOME.type);
                        criteriaIncome.andEqualTo("userAppId", used.getAppUserId());
                        Income superiorIncome = incomeMapper.selectOneByExample(example);
                        partnerLv1Updatte.setPreincome(partnerLv1.getPreincome().add(superiorIncome.getShareMoney())); // 给上级贡献收益
                    }
                    partnerMapper.updateByPrimaryKeySelective(partnerLv1Updatte);
                    // 计算剩余的金额
                    surplusAmout = surplusAmout.subtract(partnerLv1GetMoney);

                }

                // 计算直营合作商分润 ========================= start

                // 查询商户分润
                Merchant merchant = merchantMapper.selectByPrimaryKey(used.getMerchantId());
                BigDecimal merchantShareRatio = merchant.getShareRatio();

                Partner partnerDirect = partner; // 直营合作商
                BigDecimal partnerGetMoney = ((new BigDecimal(100).subtract(merchantShareRatio)).divide(new BigDecimal(100))).multiply(surplusAmout);

                // 合作商实际分润比例
                BigDecimal partnerActualShareBrokerage = partnerGetMoney.divide(amountPaid).multiply(new BigDecimal(100));

                String partnerIncomeId = sid.nextShort();
                Income partnerIncome = new Income();
                partnerIncome.setId(partnerIncomeId);
                partnerIncome.setUsedId(used.getId());
                partnerIncome.setOrderId(order_id);
                partnerIncome.setTotalAmount(amountPaid); // 分润总金额
                partnerIncome.setProjectId(used.getProjectId());
                partnerIncome.setPartnerId(partnerDirect.getId()); //  合作商ID
                partnerIncome.setMerchantId(used.getMerchantId());
                partnerIncome.setStoreId(used.getStoreId());
                partnerIncome.setShareLevel(ShareLevelEnum.PARTNER.type);
                partnerIncome.setIncomeType(IncomeTypeEnum.INCOME.type);
                partnerIncome.setShareTime(shareTime);
                partnerIncome.setUserAppId(used.getAppUserId());
                partnerIncome.setShareBrokerage(partnerActualShareBrokerage); // 分润比例
                partnerIncome.setBeforeMoney(partnerDirect.getCashoutMoney()); // 分润前金额
                partnerIncome.setAfterMoney(partnerDirect.getCashoutMoney().add(partnerGetMoney)); // 分润后金额
                partnerIncome.setShareMoney(partnerGetMoney); // 分润金额
                partnerIncome.setDeviceId(basics.getRentDeviceId());
                partnerIncome.setDirectPartnerId(partner.getId());
                incomeMapper.insertIncome(partnerIncome);

                Partner partnerUpdatte = new Partner();
                partnerUpdatte.setId(partnerDirect.getId());
                partnerUpdatte.setCashoutMoney(partnerDirect.getCashoutMoney().add(partnerGetMoney)); // 可提现金额
                partnerUpdatte.setDirectTurnover(partnerDirect.getDirectTurnover().add(amountPaid)); // 直营商户贡献营业额
                partnerUpdatte.setDirectIncome(partnerDirect.getDirectIncome().add(partnerGetMoney)); // 直营商户贡献收益

                Example example = new Example(Income.class);
                Example.Criteria criteriaIncome = example.createCriteria();

                criteriaIncome.andEqualTo("usedId", used_id);
                criteriaIncome.andEqualTo("orderId", order_id);
                criteriaIncome.andEqualTo("partnerId", partnerDirect.getParentId());
                criteriaIncome.andEqualTo("shareLevel", ShareLevelEnum.PARTNER.type);
                criteriaIncome.andEqualTo("incomeType", IncomeTypeEnum.INCOME.type);
                criteriaIncome.andEqualTo("userAppId", used.getAppUserId());
                Income superiorIncome = incomeMapper.selectOneByExample(example);
                partnerUpdatte.setPreincome(partnerDirect.getPreincome().add(superiorIncome.getShareMoney())); // 给上级贡献收益
                partnerMapper.updateByPrimaryKeySelective(partnerUpdatte);


                surplusAmout = surplusAmout.subtract(partnerGetMoney);
                // 计算直营合作商分润 ========================= end

                // 商户分成 ====================  start

                // 商户获取剩下的金额
                BigDecimal merchantGetMoney = surplusAmout;

                BigDecimal merchantShareBrokerage = merchantGetMoney.divide(amountPaid).multiply(new BigDecimal(100));

                Income merchantIncome = new Income();
                String merchantIncomeId = sid.nextShort();
                merchantIncome.setId(merchantIncomeId);
                merchantIncome.setUsedId(used.getId());
                merchantIncome.setOrderId(order_id);
                merchantIncome.setTotalAmount(amountPaid); // 分润总金额
                merchantIncome.setProjectId(used.getProjectId());
                merchantIncome.setPartnerId(used.getPartnerId()); //  合作商ID
                merchantIncome.setMerchantId(used.getMerchantId());
                merchantIncome.setStoreId(used.getStoreId());
                merchantIncome.setShareLevel(ShareLevelEnum.MERCHANT.type);
                merchantIncome.setIncomeType(IncomeTypeEnum.INCOME.type);
                merchantIncome.setShareTime(shareTime);
                merchantIncome.setUserAppId(used.getAppUserId());
                merchantIncome.setShareBrokerage(merchantShareBrokerage); // 分润比例
                merchantIncome.setBeforeMoney(merchant.getCashoutMoney()); // 分润前金额
                merchantIncome.setAfterMoney(merchant.getCashoutMoney().add(merchantGetMoney)); // 分润后金额
                merchantIncome.setShareMoney(merchantGetMoney); // 分润金额
                merchantIncome.setDeviceId(basics.getRentDeviceId());
                merchantIncome.setDirectPartnerId(partner.getId());
                incomeMapper.insertIncome(merchantIncome);


                if (merchant.getPreCost().compareTo(BigDecimal.ZERO) > 0) {
                    // TODO 该商户是预付费商户
                    PreCost merchantPreCost = new PreCost();
                    merchantPreCost.setUsedId(used.getId());
                    merchantPreCost.setOrderId(order_id);
                    merchantPreCost.setProjectId(used.getProjectId());
                    merchantPreCost.setPartnerId(used.getPartnerId());
                    merchantPreCost.setMerchantId(used.getMerchantId());
                    merchantPreCost.setStoreId(used.getStoreId());
                    merchantPreCost.setPreType(1); // 来源 1 收益  2 退款
                    merchantPreCost.setUserAppId(used.getAppUserId());
                    merchantPreCost.setShareMoney(amountPaid); // 订单金额
                    merchantPreCost.setPreMonery(merchantGetMoney.multiply(new BigDecimal(-1))); // 预付费扣除金额
                    merchantPreCost.setShareBrokerage(merchantShareBrokerage); // 分润比例
                    merchantPreCost.setBeforeMoney(merchant.getPreCost()); // 预付费扣除前金额
                    merchantPreCost.setAfterMoney(merchant.getPreCost().subtract(merchantGetMoney)); // 预付费扣除后金额
                    merchantPreCost.setDeviceId(basics.getRentDeviceId());
                    merchantPreCost.setCreateTime(shareTime);
                    preCostMapper.insertSelective(merchantPreCost);

                    // 添加预付费成功，则开始更新商户信息
                    Merchant merchantUpdate = new Merchant();
                    merchantUpdate.setId(merchant.getId());
                    merchantUpdate.setPreCost(merchant.getPreCost().subtract(merchantGetMoney)); // 保存预付费金额
                    merchantUpdate.setTotalRevenue(merchant.getTotalRevenue().add(merchantGetMoney));
                    merchantMapper.updateByPrimaryKeySelective(merchantUpdate);
                } else {
                    Merchant merchantUpdate = new Merchant();
                    merchantUpdate.setId(merchant.getId());
                    merchantUpdate.setCashoutMoney(merchant.getCashoutMoney().add(merchantGetMoney));
                    merchantUpdate.setTotalRevenue(merchant.getTotalRevenue().add(merchantGetMoney));
                    merchantMapper.updateByPrimaryKeySelective(merchantUpdate);
                }

                // 商户分成 ====================  end
            }
        }
    }


    /**
     * 进行退分润操作
     *
     * @param used_id         租借订单ID
     * @param order_id        支付订单ID
     * @param refund_order_id 退款订单ID
     */
    @Transactional
    @Override
    public void refundShareMoney(String used_id, String order_id, String refund_order_id) {


        Used used = usedMapper.selectByPrimaryKey(used_id);
        Integer isM = used.getIsM();
        if (isM == 1) {
            return;
        }

        // TODO TODO  积分的扣除 end
        RefundOrder refundOrder = refundOrderMapper.selectByPrimaryKey(refund_order_id);
        // 查询该笔订单是否全额退款
        BigDecimal amountPaid = used.getAmountPaid(); // 租借记录的实付金额
        BigDecimal refundAmount = refundOrder.getRefundFee(); // 退款金额
        Date shareTime = DateUtils.getNowDate();

        if ("0".equals(used.getMerchantId()) || StringUtils.isBlank(used.getMerchantId())
                || "0".equals(used.getPartnerId()) || StringUtils.isBlank(used.getPartnerId())
                || "0".equals(used.getStoreId()) || StringUtils.isBlank(used.getStoreId())
        ) {
            // TODO 如果存在此种情况，直接分润收益归平台所有,所以退款只退平台收益
            // TODO 首先判断是否存在对应的收益订单记录
            Project project = projectMapper.selectByPrimaryKey(used.getProjectId());
            Example example = new Example(Income.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("usedId", used_id);
            criteria.andEqualTo("orderId", order_id);
            criteria.andEqualTo("projectId", project.getId());
            criteria.andEqualTo("shareLevel", ShareLevelEnum.PROJECT.type);
            criteria.andEqualTo("incomeType", IncomeTypeEnum.NOT_DEPLOYED_INCOME.type);
            example.orderBy("shareTime").desc();
            Income projectNotDeployedIncome = incomeMapper.selectOneByExample(example);
            if (projectNotDeployedIncome != null) {
                String id = sid.nextShort();
                Income income = new Income();
                income.setId(id);
                income.setUsedId(used.getId());
                income.setOrderId(order_id);
                income.setTotalAmount(refundAmount); // 退款金额
                income.setProjectId(projectNotDeployedIncome.getProjectId());
                income.setPartnerId(projectNotDeployedIncome.getPartnerId()); //  合作商ID
                income.setMerchantId(projectNotDeployedIncome.getMerchantId());
                income.setStoreId(projectNotDeployedIncome.getStoreId());
                income.setShareLevel(ShareLevelEnum.PROJECT.type);
                income.setIncomeType(IncomeTypeEnum.NOT_DEPLOYED_INCOME_REFUND.type); // 未部署设备分润退款
                income.setShareTime(shareTime);
                income.setUserAppId(used.getAppUserId());
                income.setShareBrokerage(null);
                income.setBeforeMoney(project.getCashoutMoney()); // 分润前金额
                income.setAfterMoney(project.getCashoutMoney().subtract(refundAmount)); // 分润后金额
                income.setShareMoney(refundAmount.multiply(new BigDecimal(-1))); // 退款分润金额
                income.setDeviceId(projectNotDeployedIncome.getDeviceId());
                income.setDirectPartnerId(projectNotDeployedIncome.getDirectPartnerId());
                incomeMapper.insertIncome(income);


                Project projectUpdate = new Project();
                projectUpdate.setId(project.getId());
                projectUpdate.setNotDeployedMoney(project.getNotDeployedMoney().subtract(refundAmount));
                projectMapper.updateByPrimaryKeySelective(projectUpdate);
            }
            return;
        }


        // TODO TODO  积分的扣除 start
        Example examplePointDetail = new Example(PointsDetail.class);
        Example.Criteria criteriaPointDetail = examplePointDetail.createCriteria();
        criteriaPointDetail.andEqualTo("pointType", PointTypeEnum.XIAOBAO_IS_BOUGHT.type);
        criteriaPointDetail.andEqualTo("usedId", used_id);
        PointsDetail detail = pointsDetailMapper.selectOneByExample(examplePointDetail);
        if (detail != null) {
            // 存在小宝被购买的积分增加，那么开始减积分
            Partner partnerPoint = partnerMapper.selectByPrimaryKey(detail.getWinnerId());
            if (partnerPoint != null) {

                Integer point = Integer.parseInt(configService.selectConfigByKeyNoCache("sys.extract.point"));
                PointsDetail pointsDetail = new PointsDetail();
                String pointDetailId = sid.nextShort();
                pointsDetail.setId(pointDetailId);
                pointsDetail.setPointType(PointTypeEnum.REFUND_OF_PURCHASED_XIAOBAO.type); // 小宝购买退款
                pointsDetail.setPoints((-1) * point);
                pointsDetail.setCreateTime(shareTime); // 创建时间
                pointsDetail.setUsedId(used_id);
                pointsDetail.setOrderId(order_id);
                pointsDetail.setAppUserId(used.getAppUserId());
                pointsDetail.setSourceType(1); // 合作商类型 0 平台 1 合作商
                pointsDetail.setSourceId(partnerPoint.getId());
                pointsDetail.setWinnerType(1);
                pointsDetail.setWinnerId(partnerPoint.getId());
                pointsDetailMapper.insertPointsDetail(pointsDetail);
                // 减积分
                Partner partnerUpdatteRs = new Partner();
                partnerUpdatteRs.setPoint(partnerPoint.getPoint() - point); // 减积分
                partnerUpdatteRs.setId(partnerPoint.getId());
                partnerMapper.updateByPrimaryKeySelective(partnerUpdatteRs);
            }
        }

        if (amountPaid.subtract(refundAmount).compareTo(BigDecimal.ZERO) == 0) {
            // 进行的全额退款操作,那么直接等额退款
            Example example = new Example(Income.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("usedId", used_id);
            criteria.andEqualTo("orderId", order_id);
            List<Income> incomes = incomeMapper.selectByExample(example);
            if (incomes != null && incomes.size() > 0) {
                int size = incomes.size();
                // TODO 注意退款的时候需要将对应的营业额这些数据进行操作
                boolean projectFlag = false;
                for (int i = 0; i < size; i++) {
                    Income justIncome = incomes.get(i);
                    String incomeRefundId = sid.nextShort();
                    Income createIncome = new Income();
                    createIncome.setId(incomeRefundId);
                    Integer incomeType = justIncome.getIncomeType();
                    Integer shareLevel = justIncome.getShareLevel();
                    if (shareLevel == ShareLevelEnum.PROJECT.type) {
                        // 平台收益退分润
                        Project project = projectMapper.selectByPrimaryKey(justIncome.getProjectId());
                        if (incomeType == IncomeTypeEnum.PROJECT_EXTRACT.type) {
                            // 平台抽成退分润
                            createIncome.setIncomeType(IncomeTypeEnum.PROJECT_REFUND.type); // 平台项目抽成退款
                            projectFlag = true;
                        } else if (incomeType == IncomeTypeEnum.INCOME.type) {
                            // 平台收益
                            createIncome.setIncomeType(IncomeTypeEnum.REFUND.type);
                            projectFlag = true;
                        }
                        if (projectFlag) {
                            BigDecimal projectExtractRefundMoney = justIncome.getShareMoney();
                            createIncome.setUsedId(used.getId());
                            createIncome.setOrderId(order_id);
                            createIncome.setTotalAmount(refundAmount); // 退款金额
                            createIncome.setProjectId(justIncome.getProjectId());
                            createIncome.setPartnerId(justIncome.getPartnerId()); //  合作商ID
                            createIncome.setMerchantId(justIncome.getMerchantId());
                            createIncome.setStoreId(justIncome.getStoreId());
                            createIncome.setShareLevel(ShareLevelEnum.PROJECT.type);
                            createIncome.setShareTime(shareTime);
                            createIncome.setUserAppId(justIncome.getUserAppId());
                            createIncome.setShareBrokerage(justIncome.getShareBrokerage());
                            createIncome.setBeforeMoney(project.getCashoutMoney()); // 分润前金额
                            createIncome.setAfterMoney(project.getCashoutMoney().subtract(projectExtractRefundMoney)); // 分润后金额
                            createIncome.setShareMoney(projectExtractRefundMoney.multiply(new BigDecimal(-1))); // 分润金额
                            createIncome.setDeviceId(justIncome.getDeviceId());
                            createIncome.setDirectPartnerId(justIncome.getDirectPartnerId());
                            incomeMapper.insertIncome(createIncome);

                            Project updateProject = new Project();
                            updateProject.setId(project.getId());
                            updateProject.setCashoutMoney(project.getCashoutMoney().subtract(projectExtractRefundMoney)); // 保存项目-可提现金额
                            updateProject.setExtractMoney(project.getExtractMoney().subtract(projectExtractRefundMoney)); // 抽取收益金额
                            projectMapper.updateByPrimaryKeySelective(updateProject);
                        }
                    } else if (shareLevel == ShareLevelEnum.PARTNER.type) {
                        // 合作商分润退款
                        if (incomeType == IncomeTypeEnum.INCOME.type) {
                            Partner partner = partnerMapper.selectByPrimaryKey(justIncome.getPartnerId());
                            BigDecimal partnerRefundMoney = justIncome.getShareMoney();
                            // 判断该当前执行到的合作商是否为直营合作商
                            createIncome.setUsedId(used.getId());
                            createIncome.setOrderId(order_id);
                            createIncome.setTotalAmount(refundAmount); // 退款总金额
                            createIncome.setProjectId(justIncome.getProjectId());
                            createIncome.setPartnerId(justIncome.getPartnerId()); //  合作商ID
                            createIncome.setMerchantId(justIncome.getMerchantId());
                            createIncome.setStoreId(justIncome.getStoreId());
                            createIncome.setShareLevel(ShareLevelEnum.PARTNER.type);
                            createIncome.setIncomeType(IncomeTypeEnum.REFUND.type);
                            createIncome.setShareTime(shareTime);
                            createIncome.setUserAppId(justIncome.getUserAppId());
                            createIncome.setShareBrokerage(justIncome.getShareBrokerage()); // 分润比例
                            createIncome.setBeforeMoney(partner.getCashoutMoney()); // 分润前金额
                            createIncome.setAfterMoney(partner.getCashoutMoney().subtract(partnerRefundMoney)); // 分润后金额
                            createIncome.setShareMoney(partnerRefundMoney.multiply(new BigDecimal(-1))); // 分润金额
                            createIncome.setDeviceId(justIncome.getDeviceId());
                            createIncome.setDirectPartnerId(justIncome.getDirectPartnerId());
                            incomeMapper.insertIncome(createIncome);

                            Partner partnerUpdatte = new Partner();
                            partnerUpdatte.setId(partner.getId());
                            partnerUpdatte.setCashoutMoney(partner.getCashoutMoney().subtract(partnerRefundMoney)); // 可提现金额
                            if (justIncome.getDirectPartnerId().equals(justIncome.getPartnerId())) {
                                // 当前合作商为直营合作商
                                partnerUpdatte.setDirectTurnover(partner.getDirectTurnover().subtract(refundAmount)); // 直营商户贡献营业额
                                partnerUpdatte.setDirectIncome(partner.getDirectIncome().subtract(partnerRefundMoney)); // 直营商户贡献收益
                            } else {
                                partnerUpdatte.setJuniorTurnover(partner.getJuniorTurnover().subtract(refundAmount)); // 下级贡献营业额
                                partnerUpdatte.setJuniorIncome(partner.getJuniorIncome().add(partnerRefundMoney)); // 下级贡献收益
                            }
                            // 判断该合作商是否为顶级合作商
                            if (StringUtils.isBlank(partner.getParentId()) || "0".equals(partner.getParentId())) {
                                // 顶级合作商
                                // 查询平台在该笔订单上获取到收益总额
                                // TODO 注意： 如果是99元则 平台拿抽成 ，如果不是99元 则平台拿分润
                                Example exampleTop = new Example(Income.class);
                                Example.Criteria criteriaTop = exampleTop.createCriteria();

                                criteriaTop.andEqualTo("usedId", used_id);
                                criteriaTop.andEqualTo("orderId", order_id);
                                criteriaTop.andEqualTo("projectId", justIncome.getProjectId());
                                criteriaTop.andEqualTo("shareLevel", ShareLevelEnum.PROJECT.type);
                                criteriaTop.andEqualTo("userAppId", used.getAppUserId());
                                if (amountPaid.subtract(new BigDecimal(99)).compareTo(BigDecimal.ZERO) == 0) {
                                    // 99元结束订单
                                    criteriaTop.andEqualTo("incomeType", IncomeTypeEnum.PROJECT_EXTRACT.type);
                                } else {
                                    criteriaTop.andEqualTo("incomeType", IncomeTypeEnum.INCOME.type);
                                }
                                Income superiorIncome = incomeMapper.selectOneByExample(exampleTop);
                                partnerUpdatte.setPreincome(partner.getPreincome().subtract(superiorIncome.getShareMoney())); // 给上级贡献收益
                            } else {
                                // 不是顶级合作商
                                // 查询该合作商为上级合作商的收益
                                Example exampleTop = new Example(Income.class);
                                Example.Criteria criteriaTop = exampleTop.createCriteria();

                                criteriaTop.andEqualTo("usedId", used_id);
                                criteriaTop.andEqualTo("orderId", order_id);
                                criteriaTop.andEqualTo("partnerId", partner.getParentId());
                                criteriaTop.andEqualTo("shareLevel", ShareLevelEnum.PARTNER.type);
                                criteriaTop.andEqualTo("incomeType", IncomeTypeEnum.INCOME.type);
                                criteriaTop.andEqualTo("userAppId", used.getAppUserId());
                                Income superiorIncome = incomeMapper.selectOneByExample(exampleTop);
                                partnerUpdatte.setPreincome(partner.getPreincome().subtract(superiorIncome.getShareMoney())); // 给上级贡献收益
                            }
                            partnerMapper.updateByPrimaryKeySelective(partnerUpdatte);
                        }
                    } else if (shareLevel == ShareLevelEnum.MERCHANT.type) {
                        // 商户
                        if (incomeType == IncomeTypeEnum.INCOME.type) {
                            Merchant merchant = merchantMapper.selectByPrimaryKey(justIncome.getMerchantId());
                            BigDecimal merchantRefundMoney = justIncome.getShareMoney();
                            createIncome.setUsedId(used.getId());
                            createIncome.setOrderId(order_id);
                            createIncome.setTotalAmount(refundAmount); // 分润总金额
                            createIncome.setProjectId(justIncome.getProjectId());
                            createIncome.setPartnerId(justIncome.getPartnerId()); //  合作商ID
                            createIncome.setMerchantId(justIncome.getMerchantId());
                            createIncome.setStoreId(justIncome.getStoreId());
                            createIncome.setShareLevel(ShareLevelEnum.MERCHANT.type);
                            createIncome.setIncomeType(IncomeTypeEnum.REFUND.type);
                            createIncome.setShareTime(shareTime);
                            createIncome.setUserAppId(justIncome.getUserAppId());
                            createIncome.setShareBrokerage(justIncome.getShareBrokerage()); // 分润比例
                            createIncome.setBeforeMoney(merchant.getCashoutMoney()); // 分润前金额
                            createIncome.setAfterMoney(merchant.getCashoutMoney().subtract(merchantRefundMoney)); // 分润后金额
                            createIncome.setShareMoney(merchantRefundMoney.multiply(new BigDecimal(-1))); // 分润金额
                            createIncome.setDeviceId(justIncome.getDeviceId());
                            createIncome.setDirectPartnerId(justIncome.getDirectPartnerId());
                            incomeMapper.insertIncome(createIncome);

                            if (merchant.getPreCost().compareTo(BigDecimal.ZERO) > 0) {
                                // TODO 该商户是预付费商户
                                PreCost merchantPreCost = new PreCost();
                                merchantPreCost.setUsedId(used.getId());
                                merchantPreCost.setOrderId(order_id);
                                merchantPreCost.setProjectId(used.getProjectId());
                                merchantPreCost.setPartnerId(used.getPartnerId());
                                merchantPreCost.setMerchantId(used.getMerchantId());
                                merchantPreCost.setStoreId(used.getStoreId());
                                merchantPreCost.setPreType(2); // 来源 1 收益  2 退款
                                merchantPreCost.setUserAppId(used.getAppUserId());
                                merchantPreCost.setShareMoney(refundAmount); // 订单金额
                                merchantPreCost.setPreMonery(merchantRefundMoney); // 预付费扣除金额
                                merchantPreCost.setShareBrokerage(justIncome.getShareBrokerage()); // 分润比例
                                merchantPreCost.setBeforeMoney(merchant.getPreCost()); // 预付费扣除前金额
                                merchantPreCost.setAfterMoney(merchant.getPreCost().add(merchantRefundMoney)); // 预付费扣除后金额
                                merchantPreCost.setDeviceId(justIncome.getDeviceId());
                                merchantPreCost.setCreateTime(shareTime);
                                preCostMapper.insertSelective(merchantPreCost);


                                // 添加预付费成功，则开始更新商户信息
                                Merchant merchantUpdate = new Merchant();
                                merchantUpdate.setId(merchant.getId());
                                merchantUpdate.setPreCost(merchant.getPreCost().add(merchantRefundMoney)); // 保存预付费金额
                                merchantUpdate.setTotalRevenue(merchant.getTotalRevenue().subtract(merchantRefundMoney));
                                merchantMapper.updateByPrimaryKeySelective(merchantUpdate);

                            } else {
                                Merchant merchantUpdate = new Merchant();
                                merchantUpdate.setId(merchant.getId());
                                merchantUpdate.setCashoutMoney(merchant.getCashoutMoney().subtract(merchantRefundMoney));
                                merchantUpdate.setTotalRevenue(merchant.getTotalRevenue().subtract(merchantRefundMoney));
                                merchantMapper.updateByPrimaryKeySelective(merchantUpdate);
                            }
                        }
                    }
                }
            }
        } else {
            // 不是全额退款
            Example example = new Example(Income.class);
            Example.Criteria criteria = example.createCriteria();

            criteria.andEqualTo("usedId", used_id);
            criteria.andEqualTo("orderId", order_id);
            List<Income> incomes = incomeMapper.selectByExample(example);
            if (incomes != null && incomes.size() > 0) {
                int size = incomes.size();

                BigDecimal remaining = refundAmount;
                BigDecimal proRefundGetMoney = BigDecimal.ZERO;
                // 先处理平台
                Project project = projectMapper.selectByPrimaryKey(used.getProjectId());

                Example exampleTop = new Example(Income.class);
                Example.Criteria criteriaTop = exampleTop.createCriteria();

                criteriaTop.andEqualTo("usedId", used_id);
                criteriaTop.andEqualTo("orderId", order_id);
                criteriaTop.andEqualTo("projectId", project.getId());
                criteriaTop.andEqualTo("shareLevel", ShareLevelEnum.PROJECT.type);
                criteriaTop.andEqualTo("userAppId", used.getAppUserId());

                if (amountPaid.subtract(new BigDecimal(99)).compareTo(BigDecimal.ZERO) == 0) {
                    // 99 元结束订单
                    // 查询平台抽成多少
                    Income projectIncome = incomeMapper.selectOneByExample(exampleTop);
                    BigDecimal extractMoney = projectIncome.getShareMoney(); // 平台抽成金额
                    BigDecimal surplusExtractMoney = new BigDecimal(99).subtract(extractMoney); // 平台抽成之后剩余的金额
                    BigDecimal projectNeedRefundExtractMoney = refundAmount.subtract(surplusExtractMoney); // 平台需要抽成的退款金额
                    if (projectNeedRefundExtractMoney.compareTo(BigDecimal.ZERO) > 0) {
                        // 99元退款订单，退款金额 大于 平台抽成金额之后剩余的金额，那么平台仅退款余下的金额即可
                        String incomeRefundId = sid.nextShort();
                        Income createIncome = new Income();
                        createIncome.setId(incomeRefundId);
                        createIncome.setIncomeType(IncomeTypeEnum.PROJECT_REFUND.type); // 平台项目抽成退款
                        createIncome.setUsedId(used.getId());
                        createIncome.setOrderId(order_id);
                        createIncome.setTotalAmount(refundAmount); // 退款金额
                        createIncome.setProjectId(project.getId());
                        createIncome.setPartnerId(projectIncome.getPartnerId()); //  合作商ID
                        createIncome.setMerchantId(projectIncome.getMerchantId());
                        createIncome.setStoreId(projectIncome.getStoreId());
                        createIncome.setShareLevel(ShareLevelEnum.PROJECT.type);
                        createIncome.setShareTime(shareTime);
                        createIncome.setUserAppId(projectIncome.getUserAppId());
                        createIncome.setShareBrokerage(null);
                        createIncome.setBeforeMoney(project.getCashoutMoney()); // 分润前金额
                        createIncome.setAfterMoney(project.getCashoutMoney().subtract(projectNeedRefundExtractMoney)); // 分润后金额
                        createIncome.setShareMoney(projectNeedRefundExtractMoney.multiply(new BigDecimal(-1))); // 分润金额
                        createIncome.setDeviceId(projectIncome.getDeviceId());
                        createIncome.setDirectPartnerId(projectIncome.getDirectPartnerId());
                        incomeMapper.insertIncome(createIncome);

                        Project updateProject = new Project();
                        updateProject.setId(project.getId());
                        updateProject.setCashoutMoney(project.getCashoutMoney().subtract(projectNeedRefundExtractMoney)); // 保存项目-可提现金额
                        updateProject.setExtractMoney(project.getExtractMoney().subtract(projectNeedRefundExtractMoney)); // 抽取收益金额
                        projectMapper.updateByPrimaryKeySelective(updateProject);

                        proRefundGetMoney = projectNeedRefundExtractMoney;
                        // 重置剩下的金额
                        remaining = surplusExtractMoney;
                    }
                } else {

                    Income projectIncome = incomeMapper.selectOneByExample(exampleTop);
                    BigDecimal projectShareBrokerage = projectIncome.getShareBrokerage(); // 平台分润比例
                    BigDecimal projectGetMoney = refundAmount.multiply(projectShareBrokerage).divide(new BigDecimal(100)); // 平台需要退的分润

                    String incomeRefundId = sid.nextShort();
                    Income createIncome = new Income();
                    createIncome.setId(incomeRefundId);
                    createIncome.setIncomeType(IncomeTypeEnum.PROJECT_REFUND.type); // 平台项目抽成退款
                    createIncome.setUsedId(used.getId());
                    createIncome.setOrderId(order_id);
                    createIncome.setTotalAmount(refundAmount); // 退款金额
                    createIncome.setProjectId(project.getId());
                    createIncome.setPartnerId(projectIncome.getPartnerId()); //  合作商ID
                    createIncome.setMerchantId(projectIncome.getMerchantId());
                    createIncome.setStoreId(projectIncome.getStoreId());
                    createIncome.setShareLevel(ShareLevelEnum.PROJECT.type);
                    createIncome.setShareTime(shareTime);
                    createIncome.setUserAppId(projectIncome.getUserAppId());
                    createIncome.setShareBrokerage(null);
                    createIncome.setBeforeMoney(project.getCashoutMoney()); // 分润前金额
                    createIncome.setAfterMoney(project.getCashoutMoney().subtract(projectGetMoney)); // 分润后金额
                    createIncome.setShareMoney(projectGetMoney.multiply(new BigDecimal(-1))); // 分润金额
                    createIncome.setDeviceId(projectIncome.getDeviceId());
                    createIncome.setDirectPartnerId(projectIncome.getDirectPartnerId());
                    incomeMapper.insertIncome(createIncome);

                    Project updateProject = new Project();
                    updateProject.setId(project.getId());
                    updateProject.setCashoutMoney(project.getCashoutMoney().subtract(projectGetMoney)); // 保存项目-可提现金额
                    updateProject.setExtractMoney(project.getExtractMoney().subtract(projectGetMoney)); // 抽取收益金额
                    projectMapper.updateByPrimaryKeySelective(updateProject);

                    proRefundGetMoney = projectGetMoney;
                }


                for (int i = 0; i < size; i++) {
                    Income justIncome = incomes.get(i);
                    Integer incomeType = justIncome.getIncomeType();
                    Integer shareLevel = justIncome.getShareLevel();
                    if (shareLevel == ShareLevelEnum.PARTNER.type) {
                        if (incomeType == IncomeTypeEnum.INCOME.type) {
                            // 合作商收益
                            BigDecimal partnerShareBrokerage = justIncome.getShareBrokerage();
                            BigDecimal partnerGetRefundMoney = remaining.multiply(partnerShareBrokerage).divide(new BigDecimal(100));

                            Partner partner = partnerMapper.selectByPrimaryKey(justIncome.getPartnerId());
                            Income createIncome = new Income();
                            String incomeRefundId = sid.nextShort();
                            createIncome.setId(incomeRefundId);
                            createIncome.setUsedId(used.getId());
                            createIncome.setOrderId(order_id);
                            createIncome.setTotalAmount(refundAmount); // 退款总金额
                            createIncome.setProjectId(justIncome.getProjectId());
                            createIncome.setPartnerId(justIncome.getPartnerId()); //  合作商ID
                            createIncome.setMerchantId(justIncome.getMerchantId());
                            createIncome.setStoreId(justIncome.getStoreId());
                            createIncome.setShareLevel(ShareLevelEnum.PARTNER.type);
                            createIncome.setIncomeType(IncomeTypeEnum.REFUND.type);
                            createIncome.setShareTime(shareTime);
                            createIncome.setUserAppId(justIncome.getUserAppId());
                            createIncome.setShareBrokerage(justIncome.getShareBrokerage()); // 分润比例
                            createIncome.setBeforeMoney(partner.getCashoutMoney()); // 分润前金额
                            createIncome.setAfterMoney(partner.getCashoutMoney().subtract(partnerGetRefundMoney)); // 分润后金额
                            createIncome.setShareMoney(partnerGetRefundMoney.multiply(new BigDecimal(-1))); // 分润金额
                            createIncome.setDeviceId(justIncome.getDeviceId());
                            createIncome.setDirectPartnerId(justIncome.getDirectPartnerId());
                            incomeMapper.insertIncome(createIncome);

                            Partner partnerUpdatte = new Partner();
                            partnerUpdatte.setId(partner.getId());
                            partnerUpdatte.setCashoutMoney(partner.getCashoutMoney().subtract(partnerGetRefundMoney)); // 可提现金额
                            if (justIncome.getDirectPartnerId().equals(justIncome.getPartnerId())) {
                                // 当前合作商为直营合作商
                                partnerUpdatte.setDirectTurnover(partner.getDirectTurnover().subtract(refundAmount)); // 直营商户贡献营业额
                                partnerUpdatte.setDirectIncome(partner.getDirectIncome().subtract(partnerGetRefundMoney)); // 直营商户贡献收益
                            } else {
                                partnerUpdatte.setJuniorTurnover(partner.getJuniorTurnover().subtract(refundAmount)); // 下级贡献营业额
                                partnerUpdatte.setJuniorIncome(partner.getJuniorIncome().add(partnerGetRefundMoney)); // 下级贡献收益
                            }
                            if (StringUtils.isBlank(partner.getParentId()) || "0".equals(partner.getParentId())) {
                                // 顶级合作商
                                partnerUpdatte.setPreincome(partner.getPreincome().subtract(proRefundGetMoney)); // 给上级贡献收益
                            } else {
                                // 不是顶级合作商
                                // 查询该合作商为上级合作商的收益
                                Example exampleTop1 = new Example(Income.class);
                                Example.Criteria criteriaTop1 = exampleTop1.createCriteria();
                                criteriaTop1.andEqualTo("usedId", used_id);
                                criteriaTop1.andEqualTo("orderId", order_id);
                                criteriaTop1.andEqualTo("partnerId", partner.getParentId());
                                criteriaTop1.andEqualTo("shareLevel", ShareLevelEnum.PARTNER.type);
                                criteriaTop1.andEqualTo("incomeType", IncomeTypeEnum.INCOME.type);
                                criteriaTop1.andEqualTo("userAppId", used.getAppUserId());
                                Income superiorIncome = incomeMapper.selectOneByExample(exampleTop1);
                                partnerUpdatte.setPreincome(partner.getPreincome().subtract(superiorIncome.getShareMoney())); // 给上级贡献收益
                            }
                            partnerMapper.updateByPrimaryKeySelective(partnerUpdatte);
                        }
                    } else if (shareLevel == ShareLevelEnum.MERCHANT.type) {
                        // 商户
                        if (incomeType == IncomeTypeEnum.INCOME.type) {
                            Merchant merchant = merchantMapper.selectByPrimaryKey(justIncome.getMerchantId());

                            BigDecimal merchantShareBrokerage = justIncome.getShareBrokerage();
                            BigDecimal merchantRefundMoney = refundAmount.multiply(merchantShareBrokerage).divide(new BigDecimal(100));

                            String incomeRefundId = sid.nextShort();
                            Income createIncome = new Income();
                            createIncome.setId(incomeRefundId);
                            createIncome.setUsedId(used.getId());
                            createIncome.setOrderId(order_id);
                            createIncome.setTotalAmount(refundAmount); // 分润总金额
                            createIncome.setProjectId(justIncome.getProjectId());
                            createIncome.setPartnerId(justIncome.getPartnerId()); //  合作商ID
                            createIncome.setMerchantId(justIncome.getMerchantId());
                            createIncome.setStoreId(justIncome.getStoreId());
                            createIncome.setShareLevel(ShareLevelEnum.MERCHANT.type);
                            createIncome.setIncomeType(IncomeTypeEnum.REFUND.type);
                            createIncome.setShareTime(shareTime);
                            createIncome.setUserAppId(justIncome.getUserAppId());
                            createIncome.setShareBrokerage(justIncome.getShareBrokerage()); // 分润比例
                            createIncome.setBeforeMoney(merchant.getCashoutMoney()); // 分润前金额
                            createIncome.setAfterMoney(merchant.getCashoutMoney().subtract(merchantRefundMoney)); // 分润后金额
                            createIncome.setShareMoney(merchantRefundMoney.multiply(new BigDecimal(-1))); // 分润金额
                            createIncome.setDeviceId(justIncome.getDeviceId());
                            createIncome.setDirectPartnerId(justIncome.getDirectPartnerId());
                            incomeMapper.insertIncome(createIncome);

                            if (merchant.getPreCost().compareTo(BigDecimal.ZERO) > 0) {
                                // TODO 该商户是预付费商户
                                PreCost merchantPreCost = new PreCost();
                                merchantPreCost.setUsedId(used.getId());
                                merchantPreCost.setOrderId(order_id);
                                merchantPreCost.setProjectId(used.getProjectId());
                                merchantPreCost.setPartnerId(used.getPartnerId());
                                merchantPreCost.setMerchantId(used.getMerchantId());
                                merchantPreCost.setStoreId(used.getStoreId());
                                merchantPreCost.setPreType(2); // 来源 1 收益  2 退款
                                merchantPreCost.setUserAppId(used.getAppUserId());
                                merchantPreCost.setShareMoney(refundAmount); // 订单金额
                                merchantPreCost.setPreMonery(merchantRefundMoney); // 预付费扣除金额
                                merchantPreCost.setShareBrokerage(justIncome.getShareBrokerage()); // 分润比例
                                merchantPreCost.setBeforeMoney(merchant.getPreCost()); // 预付费扣除前金额
                                merchantPreCost.setAfterMoney(merchant.getPreCost().add(merchantRefundMoney)); // 预付费扣除后金额
                                merchantPreCost.setDeviceId(justIncome.getDeviceId());
                                merchantPreCost.setCreateTime(shareTime);
                                preCostMapper.insertSelective(merchantPreCost);


                                // 添加预付费成功，则开始更新商户信息
                                Merchant merchantUpdate = new Merchant();
                                merchantUpdate.setId(merchant.getId());
                                merchantUpdate.setPreCost(merchant.getPreCost().add(merchantRefundMoney)); // 保存预付费金额
                                merchantUpdate.setTotalRevenue(merchant.getTotalRevenue().subtract(merchantRefundMoney));
                                merchantMapper.updateByPrimaryKeySelective(merchantUpdate);

                            } else {
                                Merchant merchantUpdate = new Merchant();
                                merchantUpdate.setId(merchant.getId());
                                merchantUpdate.setCashoutMoney(merchant.getCashoutMoney().subtract(merchantRefundMoney));
                                merchantUpdate.setTotalRevenue(merchant.getTotalRevenue().subtract(merchantRefundMoney));
                                merchantMapper.updateByPrimaryKeySelective(merchantUpdate);
                            }
                        }
                    }
                }
            }
        }

    }

    @Override
    public List<IncomeTrend> selectIncomeByTrendDay(Map<String, String> map) {
        return incomeMapper.selectIncomeByTrendDay(map);
    }

    @Override
    public List<IncomeTrend> selectIncomeByTrendMonth(Map<String, String> map) {
        return incomeMapper.selectIncomeByTrendMonth(map);
    }

    @Override
    public List<IncomeTrend> selectIncomeByTrendWeek(Map<String, String> map) {
        return incomeMapper.selectIncomeByTrendWeek(map);
    }

    /**
     * 贡献收支明细 (门店贡献收支明细)
     *
     * @param map
     * @return
     */
    @Override
    public List<Income> incomeRecordByMap(Map<String, String> map) {
        return incomeMapper.incomeRecordByMap(map);
    }

    /**
     * 账单明细
     *
     * @param incomeBO
     * @return
     */
    @Override
    public List<IncomeVO> selectOnlyIncomeVOList(IncomeBO incomeBO) {
        return incomeMapper.selectOnlyIncomeVOList(incomeBO);
    }

    /**
     * 查询该账号在此租借订单，拿到的收益
     *
     * @param usedId
     * @param accountId
     * @param accountType
     * @return
     */
    @Override
    public BigDecimal selectAccountByUsedId(String usedId, String accountId, int accountType) {
        return incomeMapper.selectAccountByUsedId(usedId, accountId, accountType);
    }

    /**
     * 收益数据列表
     *
     * @param incomeBO
     * @return
     */
    @Override
    public List<IncomeVO> selectIncomeVOList(IncomeBO incomeBO) {
        return incomeMapper.selectIncomeVOList(incomeBO);
    }
}
